package com.design.android.personnel;

import android.app.Application;
import com.design.android.personnel.bean.LoggedInUser;

import java.io.*;

/**
 * 全局上下文
 *
 * @author admin
 */
public class AppContext extends Application {
    private static final String AUTH = "auth";

    private static AppContext appContext;

    private static Integer loggedInUserId;
    private static LoggedInUser loggedInUser;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this;

        File file = new File(getExternalCacheDir(), AUTH);
        if (file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);

                LoggedInUser loggedInUser = (LoggedInUser) inputStream.readObject();

                inputStream.close();
                fileInputStream.close();

                setLoggedInUser(loggedInUser);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            }
        }
    }

    public static AppContext getAppContext() {
        return appContext;
    }

    public static Integer getLoggedInUserId() {
        return loggedInUserId;
    }

    public static void setLoggedInUserId(Integer loggedInUserId) {
        AppContext.loggedInUserId = loggedInUserId;
    }

    public static LoggedInUser getLoggedInUser() {
        return loggedInUser;
    }

    public static void setLoggedInUser(LoggedInUser loggedInUser) {
        AppContext.loggedInUser = loggedInUser;
        getAppContext().saveLoginCache(loggedInUser);
    }

    private void saveLoginCache(LoggedInUser loggedInUser) {
        File file = new File(getExternalCacheDir(), AUTH);

        if (loggedInUser == null || loggedInUser.getUser() == null) {
            if (file.exists()) {
                file.delete();
            }
            return;
        }

        try {
            AppContext.loggedInUserId = loggedInUser.getUser().getId();

            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(file);
            ObjectOutputStream objectInputStream = new ObjectOutputStream(outputStream);

            objectInputStream.writeObject(loggedInUser);

            objectInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
